package com.wrb.appointment.response;

import com.github.pagehelper.Page;
import com.wrb.appointment.exception.ServiceException;
import lombok.Data;
import org.springframework.http.ResponseEntity;

/**
 * 相应包装
 *
 * @author wrb
 * @date 2019/11/25 15:11
 */
@Data
public class ServerResponse<T> {

	private T data;
	private String msg;
	private int code;

	public ServerResponse(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	public static ResponseEntity success() {
		ServerResponse object = new ServerResponse(ResponseCode.SUCCESS, "success");
		return ResponseEntity.status(200).body(object);
	}

	public static <T> ResponseEntity success(T data) {
		ServerResponse object = new ServerResponse(ResponseCode.SUCCESS, "success");
		object.setData(data);
		return ResponseEntity.status(200).body(object);
	}

	public static ResponseEntity error(int code, String msg) {
		ServerResponse object = new ServerResponse(code, msg);
		return ResponseEntity.status(200).body(object);

	}

	public static <T> ResponseEntity successWithPageHelper(T data, Page page) {
		ServerResponse object = new ServerResponse(ResponseCode.SUCCESS, "success");
		PageModel pageModel = new PageModel();
		pageModel.setPageNo(page.getPageNum());
		pageModel.setPageSize(page.getPageSize());
		pageModel.setTotal(page.getTotal());
		pageModel.setPages(page.getPages());
		pageModel.setList(data);
		object.setData(pageModel);
		return ResponseEntity.status(200).body(object);
	}

	public static <T> T parseResponse(ServerResponse<T> response) throws ServiceException {
		if (response == null) {
			throw new ServiceException(100000,"内部错误");
		}
		//响应错误
		if (response.getCode() != 0) {
			throw new ServiceException(response.getCode(), response.getMsg());
		}
		return response.getData();
	}
}
